package com.isunland.managesystem.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.HashMap;
import java.util.UUID;
import org.json.JSONException;

/**
 * Created by wu on 2016/4/22.
 * 员工奖惩积分填报
 */
public class StaffScoreAddFragment extends StaffScoreBaseFragment implements View.OnClickListener {

  private String mId;
  private String mSubmitId;

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTitleCustom(R.string.fillScore);
  }

  /**
   * 初始化数据
   */
  protected void bindData() {
    mtv_scoreContent.setEnabled(false);
    mll_filScoreDetail.setVisibility(View.GONE);
    mll_departmentScore.setVisibility(View.GONE);
    mTv_addScoreType.setOnClickListener(this);
  }

  @Override public void onClick(View v) {
    switch (v.getId()) {
      case R.id.tv_addScoreType:
        if (TextUtils.isEmpty(mTv_addPersonalScore.getText().toString())) {
          ToastUtil.show(R.string.firstChooseScore);
          return;
        }
        Intent intent = new Intent(getActivity(), ScoreContentListActivity.class);
        intent.putExtra(ScoreContentListFragment.EXTRA_DEPTCODE, mDeptCode);
        startActivityForResult(intent, REQUEST_SCORE_TYPE);
        break;
      default:
        break;
    }
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
      // 响应返回图标
      case android.R.id.home:
        getActivity().finish();
        break;

      case R.id.menu_item_submit:
        if (mUsabeAddScore == null) {

          VolleyPostGetScore();
          return true;
        }

        if (mUsabeAddScore.equalsIgnoreCase("0") && mUsablePlusScore.equalsIgnoreCase("0")) {
          ToastUtil.show(R.string.zoreoScoreCannotFill);
          return true;
        }
        if (TextUtils.isEmpty(mTv_addPersonalScore.getText().toString())) {
          ToastUtil.show(R.string.choosePersonScore);
          return true;
        }

        if (TextUtils.isEmpty(mTv_addScoreType.getText().toString())) {
          ToastUtil.show(R.string.chooseTypeScore);
          return true;
        }

        if (TextUtils.isEmpty(meT_addScores.getText().toString()) && TextUtils.isEmpty(
            meT_plusScores.getText().toString())) {
          ToastUtil.show(R.string.fillAddOrPlusScore);
          return true;
        }

        //不能超过剩余可派奖励积分
        if (!TextUtils.isEmpty(meT_addScores.getText().toString())) {
          String mJolength[] = mjobNos.split(",");
          int number = mJolength.length;//奖惩人员个数
          int addScore = Integer.parseInt(mUsabeAddScore);
          int putAddScore = Integer.parseInt(meT_addScores.getText().toString());
          if (addScore < putAddScore * number) {
            ToastUtil.show(R.string.cannotOverAdd);
            return true;
          }
        }

        //不能超过剩余可派扣减积分
        if (!TextUtils.isEmpty(meT_plusScores.getText().toString())) {
          String mJolength[] = mjobNos.split(",");
          int number = mJolength.length;//奖惩人员个数
          int plusScore = Integer.parseInt(mUsablePlusScore);
          int putPlusScore = Integer.parseInt(meT_plusScores.getText().toString());
          if (plusScore < putPlusScore * number) {
            ToastUtil.show(R.string.cannotOverPlus);
            return true;
          }
        }

        //奖励积分不能超过最大限定分值
        if (!TextUtils.isEmpty(maxLimitScore) && !TextUtils.isEmpty(
            meT_addScores.getText().toString())) {
          if (Double.parseDouble(maxLimitScore) < Double.parseDouble(
              meT_addScores.getText().toString())) {
            ToastUtil.show(R.string.addScoreCanNotOver);
            return true;
          }
        }

        //奖励分值不能小于最小分值限定
        if (!TextUtils.isEmpty(minLimitScore) && !TextUtils.isEmpty(
            meT_addScores.getText().toString())) {
          if (Double.parseDouble(minLimitScore) > Double.parseDouble(
              meT_addScores.getText().toString())) {
            ToastUtil.show(R.string.scoreCanNotLow);
            return true;
          }
        }

        //扣减积分不能超过最大限定分值
        if (!TextUtils.isEmpty(maxLimitScore) && !TextUtils.isEmpty(
            meT_plusScores.getText().toString())) {
          if (Double.parseDouble(maxLimitScore) < Double.parseDouble(
              meT_plusScores.getText().toString())) {
            ToastUtil.show(R.string.plusScoreCanNotOver);
            return true;
          }
        }

        //扣减分值不能小于最小分值限定
        if (!TextUtils.isEmpty(minLimitScore) && !TextUtils.isEmpty(
            meT_plusScores.getText().toString())) {
          if (Double.parseDouble(minLimitScore) > Double.parseDouble(
              meT_plusScores.getText().toString())) {
            ToastUtil.show(R.string.pluScoreCanNotLow);
            return true;
          }
        }

        //奖惩积分必须是分值系数的倍数
        if (!TextUtils.isEmpty(mScoreFactore)) {
          double getFactor = Double.parseDouble(mScoreFactore);
          if (!TextUtils.isEmpty(meT_addScores.getText().toString())) {
            double addFactor = Double.parseDouble(meT_addScores.getText().toString());
            if (addFactor % getFactor != 0) {
              ToastUtil.show(R.string.mustMultiple);
              return true;
            }
          }

          if (!TextUtils.isEmpty(meT_plusScores.getText().toString())) {
            double plusFactor = Double.parseDouble(meT_plusScores.getText().toString());

            if (plusFactor % getFactor != 0) {
              ToastUtil.show(R.string.mustMultiple);
              return true;
            }
          }
        }

        if (!TextUtils.isEmpty(mjobNos)) {
          String mJolength[] = mjobNos.split(",");
          StringBuilder builder = new StringBuilder();
          StringBuilder buffer = new StringBuilder();
          String id;
          for (String aMJolength : mJolength) {
            id = UUID.randomUUID().toString();
            builder.append(id).append(",").toString();
            buffer.append("'").append(id).append("'").append(",").toString();
          }

          mId = builder.subSequence(0, builder.length() - 1).toString();
          mSubmitId = buffer.subSequence(0, buffer.length() - 1).toString();
        }

        AlertDialog.Builder submitDialog = new AlertDialog.Builder(getActivity());
        submitDialog.setTitle(R.string.restart_title);
        submitDialog.setMessage(R.string.requisition_submit_hint);
        submitDialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
          @Override public void onClick(DialogInterface dialog, int which) {
            volleyPostSave();
          }
        });
        submitDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
          @Override public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
          }
        });
        submitDialog.create().show();
        break;

      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  /**
   * 提交
   */

  private void volleyPostSave() {

    HashMap<String, String> params = new HashMap<>();
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_Fill_SCORE);
    params.put("id", mId);
    params.put("inStaffIds", mjobNos);

    if (!TextUtils.isEmpty(meT_addScores.getText().toString())) {
      params.put("rewValue", meT_addScores.getText().toString());
    }
    if (!TextUtils.isEmpty(meT_plusScores.getText().toString())) {
      params.put("punValue", meT_plusScores.getText().toString());
    }
    params.put("rewardKindName", mTypeName);
    params.put("rewardKindCode", mTypeCode);

    if (!TextUtils.isEmpty(mTv_addScoreDescription.getText().toString())) {
      params.put("rewardCom", mTv_addScoreDescription.getText().toString());
    }

    if (!TextUtils.isEmpty(mRewardContent)) {
      params.put("remark", mRewardContent);
    }
    if (!TextUtils.isEmpty(maxLimitScore)) {
      params.put("maxLimitScore", maxLimitScore);
    } else {
      params.put("maxLimitScore", "");
    }

    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        MyUtils.dismissDialog();
        SuccessMessage success = new Gson().fromJson(arg0, SuccessMessage.class);
        String result = success.getResult();
        String message = success.getMessage();
        if (SuccessMessage.SUCCESS.equalsIgnoreCase(result)) {
          volleyPostSubmit();
        }

        if (SuccessMessage.FAILURE.equalsIgnoreCase(result)) {
          MyUtils.show(getActivity(), message);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        MyUtils.show(getActivity(), R.string.save_failure);
      }
    });
  }

  /**
   * 提交审核
   */
  private void volleyPostSubmit() {
    HashMap<String, String> params = new HashMap<>();
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_SCORE_SUBMIT);
    params.put("memberCode", CurrentUser.newInstance(getActivity()).getMemberCode());
    params.put("ids", mSubmitId);
    params.put("dataStatus", "submit");

    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        MyUtils.dismissDialog();
        SuccessMessage success = new Gson().fromJson(arg0, SuccessMessage.class);
        String resutl = success.getResult();
        String message = success.getMessage();
        if (SuccessMessage.SUCCESS.equalsIgnoreCase(resutl)) {
          ToastUtil.show(R.string.submit_success);
          MyUtils.dismissDialog();
          getActivity().setResult(Activity.RESULT_OK);
          getActivity().finish();
        }

        if (SuccessMessage.FAILURE.equalsIgnoreCase(resutl)) {
          MyUtils.show(getActivity(), message);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        MyUtils.show(getActivity(), R.string.submit_failure);
        LogUtil.e("arg0===" + arg0);
      }
    });
    //LogUtil.e("params===" + params);
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_submit_score, menu);
    super.onCreateOptionsMenu(menu, inflater);
  }
}
